<template>
  <div>
    <el-upload class="avatar-uploader" :action="httpurl" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
      <img v-if="value" :src="imageUrl" class="avatar"  :style="`width:${width}px;height:${height}px;`" />
      <i v-else class="el-icon-plus avatar-uploader-icon" :style="`width:${width}px;height:${height}px;line-height:${height}px;`"></i>
      <div slot="tip" v-if="tip" class="el-upload__tip">只能上传jpeg/jpg/png文件，且不超过100kb。建议尺寸{{`${width}px * ${height}px`}}</div>
    </el-upload>
  </div>
</template>
<script>
export default {
  props:{
    value: {
      type: String,
      default: ''
    },
    width: {
      type: Number,
      default: 50
    },
    height: {
      type: Number,
      default: 50
    },
    tip:{
      type:Boolean,
      default:true
    }
  },
  data() {
    return {
      httpurl : this.$http.BASEURL + '/upload/uploadFile',
    }
  },
  computed: {
    imageUrl(){
      return this.$http.staticURL + this.value
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log(res,456);
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.$emit('input',res.data.url)
    },
    beforeAvatarUpload(file) {
      console.log(file,123);
      
      if (!/\.(jpg|jpeg|png|JPG|PNG|)$/.test(file.name)) {
        this.$message.error('图片类型必须是,jpeg,jpg,png,中的一种')
        return false
      } else if (file.size > 500000) {
        this.$message.error('文件大小必须小于500KB！')
        return false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  // font-size: 28px;
  color: #8c939d;
  text-align: center;
}
.avatar {

  display: block;
}
</style>

